package com.o2opuzi.pub.intercepter

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;

import com.alibaba.fastjson.JSON;
import com.o2opuzi.lib.util.AESUtils;
import com.o2opuzi.lib.util.PasswordUtils;
import com.o2opuzi.lib.web.AbstractIntercepter;
import com.o2opuzi.lib.web.WebHelper;
import com.o2opuzi.lib.web.WebHelperImpl
import com.o2opuzi.pub.component.AppComponent;
import com.o2opuzi.pub.dao.RoleDao;
import com.o2opuzi.pub.model.Menu;
import com.o2opuzi.pub.model.Role;
import com.o2opuzi.pub.model.User;
import com.o2opuzi.pub.model.UserLoginLog;
import com.o2opuzi.pub.model.UserOptLog;
import com.o2opuzi.pub.service.UserService;
import com.o2opuzi.pub.vo.UserLoginVo;

class AdminAuthIntercepter extends AbstractIntercepter{
	
	def AppComponent appComponent;
	
	private ExecutorService executorService = Executors.newCachedThreadPool();
	
	private UserService userService;
	
	private final static int CODE_NOT_LOGIN = 1;
	
	private final static int CODE_NOT_AUTH = 2;
	
	
	def result(WebHelper helper,int code){
		def ret = [:];
		boolean isAjaxRequest = false;
		String contentType =  helper.getRequest().getContentType();
		if(contentType != null){
			isAjaxRequest = contentType.indexOf("application/json") != -1;
		}
		if(code == CODE_NOT_LOGIN){
			helper.removeCookie("sid");
			helper.removeSessionAttr("adminLogin");
			ret["code"] = -200;
			if(helper.isGet()){
				if(!isAjaxRequest){
					helper.getResponse().sendRedirect("/admin/login");
					return;
				}
			}
		}
		if(code == CODE_NOT_AUTH){
			ret["code"] = -201;
		}
		helper.getResponse().setContentType("application/json;charset=utf-8");
		helper.getResponse().getWriter().write(JSON.toJSONString(ret));
	}

	@Override
	public boolean handle(HttpServletRequest request,HttpServletResponse response) throws Exception {
		WebHelper helper = new WebHelperImpl(request, response, null, null);
		def loginMap = helper.sessionAttr("adminLogin");
		if(loginMap == null){
			//检测是否登录;
			Cookie sid = WebUtils.getCookie(request, "sid");
			if(sid ==null){
				result(helper,CODE_NOT_LOGIN);
				return false;
			}
			try {
				def user =  JSON.parseObject(AESUtils.decrypt(sid.getValue()),Map.class);
				if(userService == null){
					userService = appComponent.getApplicationContext().getBean(UserService.class);
				}
				User loginuser = userService.login(new UserLoginVo(
					user["account"],
					PasswordUtils.encrypt(user["password"]),
					helper.getIpAddress(),
					helper.getClientType(),
					true,
					UserLoginLog.LOGIN_TYPE_AUTO
				));
				//获取角色信息
				Role role = appComponent.getApplicationContext().getBean(RoleDao.class).findById(loginuser.role_id);
				Set<String> menuSet = new HashSet<String>();
				if(!StringUtils.isEmpty(role.menu_auth)){
					String[] strings = role.menu_auth.split(",");
					for (String str : strings) {
						menuSet.add(str);
					}
				}
				loginMap = ["user":loginuser,"role":[name:role.name,menu:menuSet]];
				//写入session	
				helper.sessionAttr("adminLogin",loginMap);
			} catch (Exception e) {
				result(helper, CODE_NOT_LOGIN);
				return false;
			}
		}
		def user = loginMap["user"];
		def role = loginMap["role"];
		//获取菜单
		Map sysMenuMap = appComponent.getSysMenuMap();
		String path = request.getServletPath();
		//访问的url在菜单中存在.
		if(sysMenuMap.containsKey(path)){
			Menu menu = sysMenuMap[path];
			Set<String> object = (Set<String>) role["menu"];
			//检测是否有访问权限
			if(!object.contains(menu.id.toString())){
				result(helper, CODE_NOT_AUTH);
				return false;
			}
			return true;
		}
		return true;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) throws Exception {
		if(userService == null){
			userService = appComponent.getApplicationContext().getBean(UserService.class);
		}
		try {
				WebHelper helper = new WebHelperImpl(request, response, null, null);
				if(helper.isPost()){
					User user = helper.sessionAttr("adminLogin")["user"];
					UserOptLog optlog = new UserOptLog();
					optlog.http_method = request.getMethod();
					optlog.http_url = request.getServletPath();
					optlog.ipaddress = helper.getIpAddress();
					optlog.user_id = user.id;
					optlog.user_account = user.account;
					optlog.setOptdate(new Date());
					userService.addUserOptLog(optlog);
				}
		} catch (Exception e) {
			e.printStackTrace()
		}
	}
}
